package com.zhongan.usercenter.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.lang.reflect.Method;

/**
 * redis配置类
 *
 * @author za-shaojian
 * @create 2017-09-21 14:06
 **/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}

	@SuppressWarnings("rawtypes")
	@Bean
	public CacheManager cacheManager(RedisTemplate redisTemplate) {
		RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
		// 设置缓存过期时间
		rcm.setDefaultExpiration(60);// 秒
		return rcm;
	}

	/**
	 * jackson2Json序列化redis
	 * @param factory
	 * @param jackson2JsonRedisSerializer
	 * @return
	 */
	@Bean
	@SuppressWarnings("rawtypes")
	public RedisTemplate<String, String> redisTemplate1(RedisConnectionFactory factory, RedisSerializer jackson2JsonRedisSerializer) {
		StringRedisTemplate template = new StringRedisTemplate(factory);
		template.setValueSerializer(jackson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}

	@Bean
	@SuppressWarnings("rawtypes")
	public RedisSerializer fastJson2JsonRedisSerializer() {
		return new FastJson2JsonRedisSerializer<Object>(Object.class);
	}

	/**
	 * fastjson序列化redis对象
	 * @param factory
	 * @param fastJson2JsonRedisSerializer
	 * @return
	 */
	@Bean
	@SuppressWarnings("rawtypes")
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory, RedisSerializer fastJson2JsonRedisSerializer) {
		StringRedisTemplate template = new StringRedisTemplate(factory);
		template.setValueSerializer(fastJson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}

}